package cube.net.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

import cube.data.util.DataUtil;
import cube.io.StreamUtil;
import cube.utils.TimeUtil;
import static cube.utils.BaseUtil.log;
import static cube.utils.BaseUtil.msg;
import static cube.utils.BaseUtil.conf;

/**
 * Socket连接实现
 * 
 * @author abiao
 */
public class SocketConnectImpl implements SocketConnect {

    /**
     * 接收数据缓存大小
     */
    private static int BUFF_SIZE = conf.getInt("socket.buff.size");

    /**
     * 默认心跳间隔
     */
    private static final int HEART_INTERVAL = conf.getInt("heart.interval");

    private String ip;
    private int port;

    private Socket socket;
    private OutputStream os;
    private InputStream is;

    private boolean startHeart;
    private int heartBeatInterval = HEART_INTERVAL;

    private boolean connected;
    private boolean alived;
    private byte[] buff = new byte[BUFF_SIZE];

    /**
     * SocketConnectImpl
     */
    public SocketConnectImpl(String ip, int port) {
        this.ip = ip;
        this.port = port;
        this.connect();
        this.initHeartBeat();
    }

    /**
     * SocketConnectImpl
     */
    public SocketConnectImpl(Socket socket) {
        this.socket = socket;
        initSocketParam(socket);
        this.initStream();
    }

    /**
     * 初始化套接字参数
     */
    private void initSocketParam(Socket socket) {
        if (socket != null) {
            this.ip = socket.getInetAddress().getHostAddress();
            this.port = socket.getPort();
            connected = socket.isConnected();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void connect() {
        this.initSocket();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getIP() {
        return ip;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getPort() {
        return port;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isConnected() {
        return connected;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void reconnect() {
        destroyConnect();
        connect();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized boolean send(byte[] data) {
        boolean success = sendData(data);
        if (!success) {
            reconnect();
        }
        return success;
    }

    /**
     * {@inheritDoc}
     */
    public boolean send(String s) {
        return send(s.getBytes());
    }

    /**
     * 发送数据
     */
    private boolean sendData(byte[] data) {
        boolean sendSuccess = false;
        try {
            if (os != null) {
                os.write(data);
                os.flush();
                sendSuccess = true;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return sendSuccess;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void close() {
        connected = false;
        destroyConnect();
    }

    /**
     * 摧毁链接
     */
    private void destroyConnect() {
        try {
            StreamUtil.close(socket, os, is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String identify() {
        return ip + ":" + port;
    }

    /**
     * 输入流数据处理
     */
    private void handleInputStream() {
        new Thread() {
            public void run() {
                handleRecv();
            }
        }.start();
    }

    /**
     * 处理接收数据
     */
    private void handleRecv() {
        try {
            int len;
            while ((len = is.read(buff)) != -1) {
                recv(this, DataUtil.copy(buff, 0, len));
            }
            close();
        } catch (SocketException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Socket连接
     */
    private void initSocket() {
        try {
            this.socket = new Socket(ip, port);
            this.initStream();
            connected = true;
            msg.debug("socket.connect.success", ip, port);
        } catch (Exception e) {
            connected = false;
            msg.error("socket.connect.failure", ip, port, e.getMessage());
        }
    }

    /**
     * 初始化流
     */
    private void initStream() {
        try {
            if (socket != null) {
                os = socket.getOutputStream();
                is = socket.getInputStream();
            }
            handleInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * toString方法
     */
    public String toString() {
        return identify();
    }

    /**
     * hashCode
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((ip == null) ? 0 : ip.hashCode());
        result = prime * result + port;
        return result;
    }

    /**
     * equals
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SocketConnectImpl other = (SocketConnectImpl) obj;
        if (ip == null) {
            if (other.ip != null)
                return false;
        } else if (!ip.equals(other.ip))
            return false;
        if (port != other.port)
            return false;
        return true;
    }

    /**
     * 接收数据并获取连接时，覆盖此方法
     */
    public void recv(SocketConnect conn, byte[] data) {
        recv(data);
    }

    /**
     * 接收数据时，覆盖此方法
     */
    public void recv(byte[] data) {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setAutoReconnect(boolean auto) {
        if (auto && !startHeart) {
            this.initHeartBeat();
        }
        this.startHeart = auto;
    }

    /**
     * 初始化心跳服务
     */
    private void initHeartBeat() {
        new Thread() {
            public void run() {
                while (startHeart) {
                    boolean isAlive = sendHeart();
                    heartbeat(isAlive);
                    alived = isAlive;
                    if (!isAlive) {
                        msg.error("heart.failure", ip, port);
                        reconnect();
                    }
                    TimeUtil.sleep(heartBeatInterval);
                }
            }
        }.start();
    }

    /**
     * 心跳通信是否成功
     */
    private void heartbeat(boolean isAlive) {
        if (alived && !isAlive) {
            connectLost(this);
        }
        if (!alived && isAlive) {
            connectGain(this);
        }
    }

    /**
     * 连接丢失
     */
    public void connectLost(SocketConnect conn) {
    }

    /**
     * 连接获得
     */
    public void connectGain(SocketConnect conn) {
    }

    /**
     * 发送紧急心跳包
     */
    private boolean sendHeart() {
        boolean heart = false;
        try {
            if (socket != null) {
                socket.sendUrgentData(0xff);
                socket.sendUrgentData(0xff);
                heart = true;
            }
        } catch (IOException e) {
        }
        return heart;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setAutoReconnectTime(int time) {
        this.heartBeatInterval = time;
    }
}
